/**
 * Created by Administrator on 2016/6/16.
 */
/*
 * 日历插件
 * 创建时间：20160616
 * 版本：1.0.0
 */

(function($){
    var firstInvaildDate = ''; // 第一个已租日期
    var firstInvalidChooseDate = ''; // 第一个不可选日期
    var firstUnknowDate = ''; // 第一个不知道是否可选日期
    $.fn.appCalendar=function(options){
        //定义变量信息
        var defaluts={
	        ths              :'',//触发日历的输入框，用于控件不只使用一次的情况
            type              :'search',//搜索页或详情页标识
	        subType           :'',//type==search时的子类型，用于开始日期和结束日期可以是同一天 eg:calendarPrice
            startMonth        :'',//入住日期
            endMonth          :'',//退房日期
            inOrOut           :true,//入住/退房标识
            addLisener        :false,//是否绑定事件，防止重复绑定
            callback          :null,
            calMonthlength    : 12,  // 房源日历修改为后端返回的月数，小猪8个月 云掌柜3个月，自己的房源12个月

            //以下是详情专用
            invalidDate       :'',//已出租日期
            invalidChooseDate :'',//房东设置的不可租日期
	        unknownDateStr: '',//道旅房子不清楚是否可租的日期
            minNights          :1,//最少入住天数
            dynamicPrice      :'',//特殊价格
            hasWeekendPrice    :false,//周末价格是否可用
            WeekendPrice       :0,//周末价格

            PricePerNight      :'',//每晚价格
            houseCalendarPrice:'',//最终的价格，如果没有，则用PricePerNight
            currency           :'￥',
            recordDisabled    : 0,        //非传入参数，作为渲染日历记录用
            recordData        : '' ,       //非传入参数，作为渲染日历记录用
            hasChangeed       : '',//是否已经修改过已租日期
            fixedparent:false, //如果日历控件是固定定位,则为true
            startText: $.i18n.prop('ccf31fa7d5a2664d9562f31b80604a79'), //开始日期显示文本
            endText: $.i18n.prop('22baa73df8223f1d8c4807986d3b9a1b')

        };//options end

        this.opts= $.extend({}, defaluts,options);


        $.fn.extend(this,appCalendar);
        this.init();
    }

    var appCalendar={
        css:function(){

            /*if($('style[attrN=1]').length==0)
            {
                var obg = $('<style attrN="1"></style>');
                obg.append('');
                $('head').append(obg);
            }*/
            $('.calendar').hide();
            $('.calendarfixed').hide();

            this.show();


        },

        /**
         * 初始化（日期控件入口）
         * */
        init:function(){

            //设置日历的样式

            if(this.opts.startMonth)//保存原来的开始日期
            {
                $(this).attr('startMonth',this.opts.startMonth);
            }
            if(this.opts.endMonth)//保存原来的开始日期
            {
                $(this).attr('endMonth',this.opts.endMonth);
            }
            if(!this.opts.inOrOut)//保存原来的开始日期
                $(this).attr('inOrOut','out');
            this.css(this);
            this.rendering('1');//生成日历

            this.liveClick();//绑定事件

        },
        /****
         * 生成日历
         * */
        rendering:function(optionFlag){ //生成日历
            try{

                this.html('');//先清空日历中的格子
                var nowDate=new Date();
                var year=nowDate.getFullYear();//获取完整年份，如2015
                var month=((nowDate.getMonth()+1)>=10)?(nowDate.getMonth()+1):'0'+(nowDate.getMonth()+1);//获取月份
                if(this.opts.startMonth)
                {
                    //如果有选定的年月份，用选定的年月份
                    year=this.opts.startMonth.substring(0,4);
                    month=this.opts.startMonth.substring(4,6);
                    var days=this.opts.startMonth.substring(6,8);

                    if(days)
                    {
                        if(parseInt(days)==this.getDaysInMonth(year,month)&& this.getSingleOption('inOrOut')&&!this.getSingleOption('endMonth')){
                            if(month < 12){
                                month=this.getNextMonth(month);
                            }else{
                                month = '01';
                                year = parseInt(year)+1;
                            }
                        }
                    }
                }
                if(this.opts.endMonth && this.getSingleOption('inOrOut') && optionFlag)//初次加载退房日期
                {
                    //如果有选定的年月份，用选定的年月份
                    year=this.opts.endMonth.substring(0,4);
                    month=this.opts.endMonth.substring(4,6);
                    var days=this.opts.endMonth.substring(6,8);

                    if(days)
                    {
                        if(parseInt(days)==this.getDaysInMonth(year,month)&& this.getSingleOption('inOrOut')&&!this.getSingleOption('endMonth')){
                            if(month < 12){
                                month=this.getNextMonth(month);
                            }else{
                                month = '01';
                                year = parseInt(year)+1;
                            }
                        }
                    }
                }
                var day_num=this.getDaysInMonth(year,month);//获取目标年月份的天数
                var startDate=new Date(year+'/'+month+'/01');//设置目标月日期
                var weekDay=startDate.getDay()?startDate.getDay():7;//判断每个月的一号是周几
                var gezi = day_num + weekDay-1;//每个月所占的空格数字 从周一开始
                //当前月份的行数
                var row = Math.ceil(gezi / 7);

                //year,month,weekDay,gezi 后面用到的四个变量

                //生成头部的title
                //console.log(month);
                var monthTitle=this.monthToText(month)+' '+year;
		//console.log(monthTitle);
                this.append('<div class="calender-header"><span class="prve-button" data-action="prev"><img src="/images/left_.png" data-action="prev"/></span><div class="acd-month-title" month-now="'+(year.toString()+month.toString())+'">'+monthTitle+'</div><span class="next-button" data-action="next"><img src="/images/right_.png" data-action="next"/></span></div>');

                //生成周
                this.append(
                    '<div class="acd-data-day"><div>' + $.i18n.prop('fa504ea486708ba90cfdf7bbed21d60d') +
                    '</div><div>' + $.i18n.prop('fa504ea486708ba90cfdf7bbed21d60e') +
                    '</div><div>' + $.i18n.prop('fa504ea486708ba90cfdf7bbed21d60f') +
                    '</div><div>' + $.i18n.prop('fa504ea486708ba90cfdf7bbed21d601') +
                    '</div><div>' + $.i18n.prop('fa504ea486708ba90cfdf7bbed21d602') +
                    '</div><div>' + $.i18n.prop('fa504ea486708ba90cfdf7bbed21d603') +
                    '</div><div>' + $.i18n.prop('fa504ea486708ba90cfdf7bbed21d604') +
                    "</div></div>"
                );

                var cdStr='<div class="acd-month-box">';//生成天的格子
                var startMonth=this.opts.startMonth;//开始年月，用最初的年月判断是否为以前的日期
                var endMonth=this.opts.endMonth;//结束日期
                var dynamicPric='';//特殊价格

                if(this.opts.dynamicPrice) {
                    dynamicPric = JSON.parse(this.opts.dynamicPrice);
                }
                var k=1;
                for(var i=0;i<row;i++)//从周一开始
                {
                    var single = '';

                    for (j = 1; j < 8; j++) {
                        if (this.opts.type == 'search')//非详情页使用
                        {
                            if (i == 0 && (j < weekDay))
                                single = '<div class="acd-day"></div>';//上个月的日期,置为空格
                            else if (k > day_num)
                                single = '<div class="acd-day"></div>';//当月最后一天之后的日期,置为空格

                            else  //当月的日期
                            {
                                var dayNum = k;

                                var dataValue = year + '' + month + '' + ((dayNum >= 10) ? dayNum : ('0' + dayNum));
                                var todayDate = this.getIntraday();
                                var showData = (todayDate == dataValue) ? $.i18n.prop('8882ce8ef460f4672535335b682f8cb5') : dayNum;//如果是今天，则显示的文字为$.i18n.prop('8882ce8ef460f4672535335b682f8cb5')
                                var className = 'acd-day-bg';
                                var dataClick = '';

                                //以下是要设为不可用或选中状态
                                if (todayDate > dataValue)//当月的今天之前的日期
                                    className = className + ' day-previous';
                                else {//今天之后的日期
                                    var oldstartMonth = this.getSingleOption('startMonth');
                                    var oldMonth = this.getSingleOption('endMonth');
                                    var inOrOut = this.getSingleOption('inOrOut');

                                    if(!inOrOut) //如果是入住日期
                                    {

                                        if(oldMonth){
                                            if (dataValue < oldstartMonth)//如果是选择过的日期之前的日期
                                            {
                                                className = className + ' data-hover';
                                                dataClick = "ok";
                                                parentClass='normalNode';

                                            }

                                            else if (dataValue == oldstartMonth) {
                                                if(dataValue == oldMonth && this.opts.subType == 'calendarPrice'){
	                                                className = className + ' day-checked';
	                                                showData = this.opts.startText || showData;
	                                                dataClick = "ok";
                                                }else{
	                                                className = className + ' day-checked day-checked-in';
	                                                showData = this.opts.startText || showData;
                                                }

                                            }
                                            else {
                                                if(dataValue > oldstartMonth && dataValue < oldMonth){
                                                    className = className + ' data-hover data-middle';
                                                    parentClass='normalNode';
                                                }
                                                else if (dataValue == oldMonth) {
                                                    className = className + ' day-checked day-checked-out';
                                                    showData = this.opts.endText || showData;
                                                }
                                                dataClick = "ok";
                                            }

                                        }
                                        else if (oldstartMonth)//用户选择过开始日期，则那个日期前的均设为不可选
                                        {
                                            if (dataValue < oldstartMonth)//如果是选择过的日期之前的日期
                                            {
                                                className = className + ' data-hover';
                                                dataClick = "ok";
                                                parentClass='normalNode';

                                            }

                                            else if (dataValue == oldstartMonth) {
                                                className = className + '  day-checked';
                                                showData = this.opts.startText || showData;
                                                if(this.opts.subType == 'calendarPrice'){
	                                                dataClick = "ok";
                                                }
                                            }
                                            else {
                                                dataClick = "ok";
                                            }

                                        }
                                        else {
                                            dataClick = "ok";
                                        }

                                    }
                                    else{
                                        if (oldMonth)//用户选择过开始日期，则那个日期前的均设为不可选
                                        {
                                            if (dataValue < oldMonth)//如果是选择过的日期之前的日期
                                            {

                                                if(dataValue>oldstartMonth)
                                                {
                                                    className = className + ' data-hover data-middle';
                                                    dataClick = "ok";
                                                    parentClass='normalNode';
                                                }
                                                else if (dataValue == oldstartMonth) {
                                                    if(this.opts.subType == 'calendarPrice'){
	                                                    className = className + ' day-checked day-checked-in';
	                                                    showData = this.opts.startText || showData;
	                                                    dataClick = "ok";
                                                    }else{
	                                                    className = className + ' day-previous day-checked day-checked-in';
	                                                    showData = this.opts.startText || showData;
                                                    }
                                                }
                                                else
                                                    className = className + ' day-previous';

                                            }

                                            else if (dataValue == oldMonth) {
	                                            if(dataValue == oldstartMonth && this.opts.subType == 'calendarPrice'){
		                                            className = className + ' day-checked';
		                                            showData = this.opts.startText || showData;
		                                            dataClick = "ok";
	                                            }else if (this.getSingleOption('endMonth')) {
                                                    showData = this.opts.endText || showData;
                                                    className = className + '  day-checked day-checked-out';
                                                }
                                                else
                                                    className = className + '  day-previous';
                                            }
                                            else {
                                                dataClick = "ok";
                                            }

                                        }
                                        else {
                                            if(dataValue<oldstartMonth)
                                            {
                                                className = className + '  day-previous';
                                            }
                                            else if (dataValue == oldstartMonth) {
	                                            if(this.opts.subType == 'calendarPrice'){
		                                            className = className + ' day-checked';
		                                            showData = this.opts.startText || showData;
		                                            dataClick = "ok";
	                                            }else{
		                                            className = className + ' day-previous day-checked';
		                                            showData = this.opts.startText || showData;
                                                }
                                            }
                                            else
                                                dataClick = "ok";
                                        }
                                    }
                                }
                                k++;


                                single = '<div class="acd-day"><div class="' + className + '" id="' + dataValue + '" data-click="' + dataClick + '">' + showData + '</div></div>';
                            }


                            cdStr = cdStr + single;

                        }

                        else //详情页使用
                        {
                            if (i == 0 && (j < weekDay))
                                single = '<div class="acd-day"></div>';//上个月的日期,置为空格
                            else if (k > day_num)
                                single = '<div class="acd-day"></div>';//当月最后一天之后的日期,置为空格
                            else  //当月的日期
                            {
                                var dayNum = k;
                                var dataValue = year + '' + month + '' + ((dayNum >= 10) ? dayNum : ('0' + dayNum));//当前循环到的日期
                                var todayDate = this.getIntraday();
                                var showData = (todayDate == dataValue) ? $.i18n.prop('8882ce8ef460f4672535335b682f8cb5') : dayNum;//如果是今天，则显示的文字为$.i18n.prop('8882ce8ef460f4672535335b682f8cb5')
                                var className = 'acd-day-bg';
                                var parentClass='';
                                var dataClick = '';
                                var details = '';
                                //以下是要设为不可用或选中状态
                                if (todayDate > dataValue)//当月的今天之前的日期 //过期日期
                                {
                                    className = className + ' day-previous';
                                    parentClass='preNode';
                                }
                                else {//今天之后的日期
                                    var oldstartMonth = this.getSingleOption('startMonth');
                                    var oldMonth = this.getSingleOption('endMonth');
                                    var inOrOut = this.getSingleOption('inOrOut');


                                    if(!inOrOut) //如果是入住日期
                                    {
                                        if (oldstartMonth)//用户选择过开始日期，则那个日期前的均设为不可选
                                        {
                                            if (dataValue < oldstartMonth)//如果是选择过的日期之前的日期
                                            {
                                                className = className + ' data-hover';
                                                if(this.opts.invalidDate.indexOf(dataValue)>=0)
                                                {
                                                    //已经出租出去了
                                                    // showData = '已租';
                                                    className = className + ' day-previous alreadySend';
                                                    parentClass='preNode aleadysendbox';
                                                }
                                                else if(this.opts.invalidChooseDate.indexOf(dataValue)>=0)
                                                {
                                                    //不可选日期
                                                    //showData = '不1';
                                                    className = className + ' day-previous notChoose';
                                                    parentClass='preNode aleadysendbox';
                                                }
                                                else if(this.opts.unknownDateStr.indexOf(dataValue)>=0)
                                                {
                                                    //不知道是否可租
                                                    //showData = '不1';
                                                    className = className + ' day-previous unknow';
                                                    parentClass='preNode aleadysendbox';
                                                }
                                                else
                                                {
                                                    className = className + ' data-hover';

                                                    dataClick = "ok";
                                                    parentClass='normalNode';
                                                }

                                            }
                                            else if (dataValue == oldstartMonth) {
                                                className = className + '  day-checked data-hover thisday';
                                                showData = this.opts.startText || showData;

                                            }
                                            else {
                                                if(this.opts.invalidDate.indexOf(dataValue)>=0)
                                                {
                                                    //已经出租出去了
                                                    // showData = '已租';
                                                    className = className + ' day-previous alreadySend';
                                                    parentClass='preNode aleadysendbox';
                                                }
                                                else if(this.opts.invalidChooseDate.indexOf(dataValue)>=0)
                                                {
                                                    //不可选日期
                                                    //showData = '不1';
                                                    className = className + ' day-previous notChoose';
                                                    parentClass='preNode aleadysendbox';
                                                }
                                                else if(this.opts.unknownDateStr.indexOf(dataValue)>=0)
                                                {
	                                                //不知道是否可租
	                                                //showData = '不1';
	                                                className = className + ' day-previous unknow';
	                                                parentClass='preNode aleadysendbox';
                                                }
                                                else
                                                {
                                                    className = className + ' data-hover';

                                                    dataClick = "ok";
                                                    parentClass='normalNode';
                                                }
                                            }

                                        }
                                        else
                                        { //在没有选择时间的情况下

                                            if(this.opts.invalidDate.indexOf(dataValue)>=0)
                                            {
                                                //已经出租出去了
                                                // showData = '已租';
                                                className = className + ' day-previous alreadySend';
                                                parentClass='preNode aleadysendbox';
                                            }
                                            else if(this.opts.invalidChooseDate.indexOf(dataValue)>=0)
                                            {
                                                //不可选日期
                                                //showData = '不1';
                                                className = className + ' day-previous notChoose';
                                                parentClass='preNode aleadysendbox';
                                            }
                                            else if(this.opts.unknownDateStr.indexOf(dataValue)>=0)
                                            {
	                                            //不知道是否可租
	                                            //showData = '不1';
	                                            className = className + ' day-previous unknow';
	                                            parentClass='preNode aleadysendbox';
                                            }
                                            else
                                            {
                                                dataClick = "ok";
                                                className = className + ' data-hover';
                                                parentClass='normalNode';
                                            }
                                        }
                                        if(oldMonth){
                                            if (dataValue == oldstartMonth) {
                                                className = className + ' day-checked day-checked-in';
                                                showData = this.opts.startText || showData;

                                            }
                                            else {
                                                if(dataValue > oldstartMonth && dataValue < oldMonth){
                                                    className = className + ' data-hover data-middle';
                                                    parentClass='normalNode';
                                                }
                                                else if (dataValue == oldMonth) {
                                                    className = className + ' day-checked day-checked-out';
                                                    showData = this.opts.endText || showData;
                                                }
                                            }
                                        }
                                    }
                                    else{  // 退房时间

                                        if(dataValue==oldstartMonth){
                                            className = className + ' day-previous day-checked';
                                            showData = this.opts.startText || showData;
                                        }
                                        else if(dataValue<oldstartMonth)
                                        {
                                            className = className + '  day-previous';

                                            if(this.opts.invalidDate.indexOf(dataValue)>=0)
                                            {
                                                //已经出租出去了
                                                // showData = '已租';
                                                className = className + ' day-previous alreadySend';
                                                parentClass='preNode aleadysendbox';

                                            }
                                            else if(this.opts.invalidChooseDate.indexOf(dataValue)>=0)
                                            {
                                                //不可选日期
                                                //showData = '不1';
                                                className = className + ' day-previous notChoose';
                                                parentClass='preNode aleadysendbox';

                                            }
                                            else if(this.opts.unknownDateStr.indexOf(dataValue)>=0)
                                            {
	                                            //不知道是否可租
	                                            //showData = '不1';
	                                            className = className + ' day-previous unknow';
	                                            parentClass='preNode aleadysendbox';
                                            }
                                        }
                                        else
                                        {
                                            if(this.opts.invalidDate.indexOf(dataValue)>=0)
                                            {
                                                //已经出租出去了
                                                // showData = '已租';
                                                className = className + ' day-previous alreadySend';
                                                parentClass='preNode aleadysendbox';

                                                if(!firstInvaildDate){
                                                    firstInvaildDate = dataValue;
                                                }

                                            }
                                            else if(this.opts.invalidChooseDate.indexOf(dataValue)>=0)
                                            {
                                                //不可选日期
                                                //showData = '不1';
                                                className = className + ' day-previous notChoose';
                                                parentClass='preNode aleadysendbox';

                                                if(!firstInvalidChooseDate){
                                                    firstInvalidChooseDate = dataValue;
                                                }
                                            }
                                            else if(this.opts.unknownDateStr.indexOf(dataValue)>=0)
                                            {
	                                            //不知道是否可租
	                                            //showData = '不1';
	                                            className = className + ' day-previous unknow';
	                                            parentClass='preNode aleadysendbox';

	                                            if(!firstUnknowDate){
		                                            firstUnknowDate = dataValue;
	                                            }
                                            }
                                            else
                                            {
                                                className = className + ' data-hover';

                                                dataClick = "ok";
                                                parentClass='normalNode';
                                            }

                                            // 已租日期以后置灰且不可选
                                            if(firstInvaildDate && dataValue > firstInvaildDate){
                                                className = className + ' day-previous';
                                                parentClass = 'preNode';
                                                dataClick = '';
                                            }
                                            // 不可选日期以后置灰且不可选
                                            if(firstInvalidChooseDate && dataValue > firstInvalidChooseDate){
                                                className = className + ' day-previous';
                                                parentClass = 'preNode';
                                                dataClick = '';
                                            }
                                            // 不知道是否可选日期以后置灰且不可选
                                            if(firstUnknowDate && dataValue > firstUnknowDate){
                                                className = className + ' day-previous';
                                                parentClass = 'preNode';
                                                dataClick = '';
                                            }


                                        }


                                        if (oldMonth)//用户选择过开始日期，则那个日期前的均设为不可选
                                        {

                                            if (dataValue == oldstartMonth) {
                                                className = className + ' day-checked day-checked-in';
                                                showData = this.opts.startText || showData;

                                            }
                                            else {
                                                if(dataValue > oldstartMonth && dataValue < oldMonth){
                                                    className = className + ' data-hover data-middle';
                                                    parentClass='normalNode';
                                                }
                                                else if (dataValue == oldMonth) {
                                                    className = className + ' day-checked day-checked-out';
                                                    showData = this.opts.endText || showData;
                                                }
                                            }
                                        }
                                    }


                                    //    //设置周末价格
                                    if(this.opts.hasWeekendPrice){
                                        //如果有周末价格

                                        if((dayNum+weekDay-1)%7 == 5 || (dayNum+weekDay-1)%7 == 6){
                                            details = Math.round(this.opts.WeekendPrice?this.opts.WeekendPrice:0);
                                        }
                                    }
                                    //设置特殊价格
                                    if(dynamicPric)
                                    {
                                        for(var m=0;m<dynamicPric.length;m++){
                                            var prices = dynamicPric[m];
                                            if(prices.chooseDate)
                                            {
                                                if(prices.chooseDate.indexOf(dataValue)>=0){
                                                    details = Math.round(prices.price?prices.price:0);
                                                    break;
                                                }
                                            }

                                        }
                                    }
                                    //如果特殊和周末价格没有的话，设置基础价格
                                    if(!details){
                                        details = Math.round(this.opts.PricePerNight?this.opts.PricePerNight:0);
                                    }
                                    if(details) {
                                        details = this.opts.currency+details;
                                    }


                                }


                                k++;
                                single = '<div class="acd-day nornalD '+parentClass+'"><div class="' + className + '" id="' + dataValue + '" data-click="' + dataClick + '" data-price="'+details+'">' + showData + '</div></div>';
                            }

                            cdStr = cdStr + single;
                        }

                    }
                }
                cdStr = cdStr + '</div>';
                if(this.opts.type == 'search')
                    cdStr+= '<div class="calender-bottom"><div class="calender-clear">' + $.i18n.prop('2b97b0f7a01f0446648397aaf11f6685') + '</div></div>';
                else
                    cdStr+='<div class="calender-bottom"><div class="calender-clear float_l">' +
                        $.i18n.prop('498599d9fe840fb5899c2393cfdd7589') +
                        '</div><div class="calender-additional-info">' +
                        $.i18n.prop('498599d9fe840fb5899c2393cfdd7580') +
                        '<span class="minNights">' +
                        (this.opts.minNights?this.opts.minNights:1) + '</span>' +
                        $.i18n.prop('244155a143b006c2c699356e29f060f7') + '</div></div>';
                this.append(cdStr);
                if(this.opts.type != 'search'&& this.getSingleOption('inOrOut'))//非搜索页，且已经选择了入住时间
                    this.setCannot(this.opts.minNights,this.getSingleOption('startMonth'));

            }
            catch(e){
                console.log('e:'+e);

            }

        },

        /***绑定事件**/
        liveClick:function(){

            var _box=this;
            var _opts=_box.opts;

            if(_opts.fixedparent){//聊天框内日历   声明两个日历控件对象,必须分开绑定事件，否则获取不到对象

                //给格子绑定事件
                $('body').off('click','.calendarfixed .acd-day-bg,.calendarfixed .acd-day-bg2').on('click','.calendarfixed .acd-day-bg,.calendarfixed .acd-day-bg2',function(){
                    var $this=$(this);
                    if($this.attr('data-click')=='ok' &&!$this.hasClass('tempCannot'))//正常可选的日期
                    {

                        var clickValue = $this.attr('id');
                        var info='';
                        var flag=0;

                        if(!_box.getSingleOption('inOrOut')){ //选择入住日期

                            // 重新选择入住时间，以下两变量置空
	                        firstInvaildDate = '';
	                        firstInvalidChooseDate = '';
	                        firstUnknowDate = '';

                            _opts.startMonth = clickValue;
                            var endMonth=_box.getSingleOption('endMonth');
                            if(endMonth)
                            {
                                if(clickValue<endMonth)
                                {
                                    flag= _box.testDate(clickValue,endMonth);

                                }
                            }
                        }
                        else{ //选择退房日期
                            _opts.endMonth = clickValue;
                            var startMonth=_box.getSingleOption('startMonth');
                            flag= _box.testDate(startMonth,clickValue);
                        }

                        if(_opts.callback != null){
                            var startMonth=_opts.startMonth;
                            if(startMonth.length!=8)
                                startMonth=_box.getSingleOption('startMonth');
                            var endMonth=_opts.endMonth;
                            if(_opts.startMonth==_opts.endMonth)
                            {
                                endMonth='';
                            }
                            var param = {
	                            ths: _opts.ths,
                                startMonth:startMonth,
                                endMonth:endMonth,
                                info:flag

                            }
                            _opts.callback(param);
                        }
                    }
                });

                //给上一月、下一月绑定点击事件
                $('body').off('click','.calendarfixed .prve-button,.calendarfixed .next-button').on('click','.calendarfixed .prve-button,.calendarfixed .next-button', function (e) {
                    var todayDate = _box.getIntraday().substr(0,6);

                    var $clendabox=$(this).parents('.calendar');
                    var $acdmonthtitle=$('.calendarfixed').find('.acd-month-title');;
                    // if($clendabox.length==0){ //是聊天框的日历
                    //     $acdmonthtitle=$('.calendarfixed').find('.acd-month-title');
                    // }
                    // else{ //是页面的日历
                    //     $acdmonthtitle=$('.calendar').find('.acd-month-title');
                    // }

                    var nowData = $acdmonthtitle.attr('month-now');
                    nowData=nowData.substring(0, 6);//展示当前月份
                    var action = $(this).attr('data-action');//获取点击动作（上个月或者下个月）
                    var selectData = _box.getMouthForAc(nowData, action);//展示下一月份
                    if(action == 'prev'&&_box.getMouthInterval(todayDate,selectData)<0 || action == 'next'&&_box.getMouthInterval(todayDate,selectData)> _box.opts.calMonthlength-1) return;

                    //重新渲染日历

                    _box.opts.startMonth=selectData;

                    _box.rendering();

                });


                //给清除按钮绑定事件
                $('body').off('click','.calendarfixed .calender-clear').on('click','.calendarfixed .calender-clear',function(){
                    if(_opts.callback != null){
                        var param = {
	                        ths: _opts.ths,
                            startMonth:'',
                            endMonth:''
                        }
                        _opts.callback(param);
                    }
                });



            }
            else{
                //给格子绑定事件
                $('body').off('click','.calendar .acd-day-bg,.calendar .acd-day-bg2').on('click','.calendar .acd-day-bg,.calendar .acd-day-bg2',function(){
                    var $this=$(this);
                    if($this.attr('data-click')=='ok' &&!$this.hasClass('tempCannot'))//正常可选的日期
                    {

                        var clickValue = $this.attr('id');
                        var info='';
                        var flag=0;

                        if(!_box.getSingleOption('inOrOut')){ //选择入住日期

                            // 重新选择入住时间，以下两变量置空
	                        firstInvaildDate = '';
	                        firstInvalidChooseDate = '';
	                        firstUnknowDate = '';

                            _opts.startMonth = clickValue;
                            var endMonth=_box.getSingleOption('endMonth');
                            if(endMonth)
                            {
                                if(clickValue<endMonth)
                                {
                                    flag= _box.testDate(clickValue,endMonth);
                                }
                            }
                        }
                        else{ //选择退房日期
                            _opts.endMonth = clickValue;
                            var startMonth=_box.getSingleOption('startMonth');
                            flag= _box.testDate(startMonth,clickValue);
                        }

                        if(_opts.callback != null){
                            var startMonth=_opts.startMonth;
                            if(startMonth.length!=8)
                                startMonth=_box.getSingleOption('startMonth');
                            var endMonth=_opts.endMonth;
                            if(_opts.startMonth==_opts.endMonth)
                            {
	                            if(_opts.subType != 'calendarPrice'){
		                            endMonth='';
                                }
                            }
                            var param = {
                                ths: _opts.ths,
                                startMonth:startMonth,
                                endMonth:endMonth,
                                info:flag
                            }
                            _opts.callback(param);
                        }
                    }
                });

                //给上一月、下一月绑定点击事件
                $('body').off('click','.calendar .prve-button,.calendar .next-button').on('click','.calendar .prve-button,.calendar .next-button', function (e) {
                    var todayDate = _box.getIntraday().substr(0,6);

                    var $clendabox=$(this).parents('.calendar');
                    var $acdmonthtitle= $acdmonthtitle=$('.calendar').find('.acd-month-title');;

                    var nowData = $acdmonthtitle.attr('month-now');
                    nowData=nowData.substring(0, 6);//展示当前月份
                    var action = $(this).attr('data-action');//获取点击动作（上个月或者下个月）
                    var selectData = _box.getMouthForAc(nowData, action);//展示下一月份
                    if(action == 'prev'&&_box.getMouthInterval(todayDate,selectData)<0 || action == 'next'&&_box.getMouthInterval(todayDate,selectData)>  _box.opts.calMonthlength-1) return;

                    //重新渲染日历

                    _box.opts.startMonth=selectData;

                    _box.rendering();

                });


                //给清除按钮绑定事件
                $('body').off('click','.calendar .calender-clear').on('click','.calendar .calender-clear',function(){
                    if(_opts.callback != null){
                        var param = {
	                        ths: _opts.ths,
                            startMonth:'',
                            endMonth:''
                        }
                        _opts.callback(param);
                    }
                });


                //鼠标弹出框事件
                if(_opts.type!='search')
                {
                    $('body').off('mouseenter mouseleave').on({
                        'mouseenter':function(){
                            var $this=$(this);
                            var top=$this.position().top-35,left=$this.position().left-18,showPrice=$this.attr('data-price');
                            if(!$this.hasClass('thisday'))
                            {
                                // $this.addClass('day-checked');
                            }

                            if(showPrice &&  showPrice != 0) {
                                _box.append('<div class="popover top" style="left:'+left+'px;top:'+top+'px"><div class="arrow"></div><div class="popover-content">'+showPrice+'</div></div>');
                            }

                        },
                        'mouseleave':function(){
                            /*var $this=$(this);
                            var top=$this.position().top-33,left=$this.position().left-15,showPrice=$this.attr('data-price');
                            if(!$this.hasClass('thisday'))
                            {
                                // $this.removeClass('day-checked');
                            }*/
                            _box.find('.popover').remove();

                        }

                    },'.data-hover:not(".day-previous,.tempCannot")');
                }
            }





            //关闭日历事件
            $(document).off('click').on('click',function (e) {
                var $etarget=$(e.target);
                if($etarget.hasClass('thisday'))
                {
                    if(!$('.calendererrorinfo').hasClass('hide'))
                        $('.calendererrorinfo').addClass('hide');
                }
                if($etarget.attr('calender-input')||$etarget.hasClass('calender-clear')||$etarget.attr('data-action')||$etarget.attr('data-click')=='ok'||$etarget.hasClass('day-previous')||$etarget.hasClass('tempCannot')||$etarget.hasClass('exceptionObj'))
                    return;
                _box.removeAttr('inOrOut oldMonth endMonth').empty().hide();
            });


        },

        /***
         * 判断某个月有多少天，如2015年10月有多少天
         * year:年份,如’2015‘
         * month:月份，如'01'
         * **/
        getDaysInMonth:function(year,month){
            return new Date(year,month,0).getDate();
        },

        /***
         * 获取当年的时间，返回值为20150102格式
         * */
        getIntraday:function(){
            var nowDate=new Date();
            var year=nowDate.getFullYear();
            var month=(nowDate.getMonth()+1>=10)?(nowDate.getMonth()+1):'0'+(nowDate.getMonth()+1);
            var day=(nowDate.getDate()>=10)?(nowDate.getDate()):'0'+(nowDate.getDate());
            return year+''+month+''+day;

        },

        /***
         * 两个时间相差的天数
         * date1 小的日期 20140505
         * date2 大的日期 20150202
         *
         * */
        getDateDeff:function(date1,date2){
            if(date1.length!=8||date2.length!=8)
                return -1;

            var tempd1=new Date(date1.substring(0,4)+'/'+date1.substring(4,6)+'/'+date1.substring(6,8));
            var tempd2=new Date(date2.substring(0,4)+'/'+date2.substring(4,6)+'/'+date2.substring(6,8));
            var daycount=parseInt(Math.abs(tempd2-tempd1)/1000/60/60/24);    //把相差的毫秒数转换为天数
            return daycount;

        },


        /**
         * 根据当前月份和动作判断下（上）一个月份的时间,如返回201610
         * nowData:当前月份，如'201510'
         *action:上个月/下个月的标识，值为'next'或’prev‘
         * */
        getMouthForAc:function(nowData,action){
            try{
                y=nowData.substring(0,4);
                m=nowData.substring(4,6);
                if(action=='next'){ //下个月的年月
                    if(m=='12'){
                        y=parseInt(y)+1;
                        y= y.toString();
                        return y+'01';

                    }
                    else{
                        m=parseInt(m)+1;
                        if(m<10)
                            m= '0'+m.toString();
                        else
                            m= m.toString();
                        return y+m;

                    }
                }//end
                else{
                    if(m=='01')
                    {
                        y=parseInt(y)-1;
                        y= y.toString();
                        return y+'12';
                    }
                    else{
                        m=parseInt(m)-1;
                        if(m<10)
                            m='0'+ m.toString();
                        else
                            m= m.toString();
                        return y+m;
                    }
                }//end

            }
            catch(e){
                console.log('parent e:'+e);
            }
        },//getMouthForAc end
        getSingleOption:function(option){
            var _this=this;
            if(_this.opts.fixedparent)
            {
                return  $('.calendarfixed').attr(option);
            }
            else{
                return  $('.calendar').attr(option);
            }

        },

        //根据月份，获取下个月份，用两位数表示
        getNextMonth:function(oldMonth)
        {
            var m=parseInt(oldMonth)+1;
            if(m<10)
                m='0'+ m.toString();
            else
                m= m.toString();
            return m;

        },
        /**根据开始时间和最小入住天数，获取用户的操作日期范围
         *startMonth 开始日期 20150606
         * minNights 最小入住天数 2
         * 返回值：[20140404,20150505]
         *  **/
        getDateByInterval:function(startMonth,minNights) {
            if (startMonth.length != 8 || !minNights)
                return;
            var y = startMonth.substring(0, 4);
            var m = startMonth.substring(4, 6);
            var day = parseInt(startMonth.substring(6, 8));

            var daysnum = this.getDaysInMonth(y, m);

            var params = [];
            var flag = 1;

            for (var i = 0; i < minNights; i++) {
                var tempm=m;
                if (day + i + 1 <= daysnum)
                {
                    var day2=day + i + 1;
                    params.push(y + tempm + (day2>=10?day2.toString():'0'+day2));
                }

                else {
                    if (tempm == '12') {
                        y = parseInt(y) + 1;
                        y = y.toString();
                        params.push(y + '01' + (flag < 10 ? ('0' + flag) : flag.toString()));
                    }
                    else {
                        tempm = parseInt(tempm) + 1;
                        if (tempm < 10)
                            tempm = '0' + tempm.toString();
                        else
                            tempm = tempm.toString();
                        params.push(y + tempm + (flag < 10 ? ('0' + flag) : flag.toString()));
                    }
                    flag++;
                }
            }
            return params;
        },


        /**
         * 根据当前年月日和动作判断下（上）一个月份的特定日期,如返回20161010(设置日期是否可出租时使用)
         * nowData:当前年月日，如'201510'
         *action:上个月/下个月的标识，值为'next'或’prev‘
         * minDay:最少入住天数，数字
         * */
        getYearMonthDayByDate:function(nowData,action,minDay){
            try{
                var tempArr=[];
                y=nowData.substring(0,4);
                m=nowData.substring(4,6);
                if(action=='next'){ //下个月的年月
                    if(m=='12'){
                        y=parseInt(y)+1;
                        y= y.toString();
                        for(var i=0;i<minDay;i++)
                        {
                            tempArr.push(y+'01'+(i+1<10?'0'+(i+1):i+1));
                        }
                        return tempArr;

                    }
                    else{
                        m=parseInt(m)+1;
                        if(m<10)
                            m= '0'+m.toString();
                        else
                            m= m.toString();

                        for(var i=0;i<minDay;i++)
                        {
                            tempArr.push(y+m+(i+1<10?'0'+(i+1):i+1));
                        }
                        return tempArr;

                    }
                }//end
                else{
                    if(m=='01')
                    {
                        y=parseInt(y)-1;
                        y= y.toString();

                        for(var i=0;i<minDay;i++)
                        {
                            tempArr.push(y+'12'+((31-i)>=10?(31-i):'0'+(31-i)));
                        }
                        return tempArr;
                    }
                    else{
                        m=parseInt(m)-1;
                        var days=this.getDaysInMonth(parseInt(y),m);//获取目标月天数
                        if(m<10)
                            m='0'+ m.toString();
                        else
                            m= m.toString();

                        for(var i=0;i<minDay;i++)
                        {
                            tempArr.push(y+m+((days-i)>=10?(days-i):'0'+(days-i)));
                        }
                        return tempArr;
                    }
                }//end

            }
            catch(e){
                console.log('parent e:'+e);
            }
        },//getMouthForAc end

        /****
         * 判断退房日期控件日期是否可以选择
         * startMonth 已选中的日期
         * minDays  最小入住天数
         * */
        setCannot:function(minDays,startMonth) {
            try{
                var _box=this;
                if(startMonth.length==8)
                {
                    var $acdstartmonth=$('.acd-day-bg[id='+startMonth+']');
                    if(!$acdstartmonth.hasClass('thisday'))
                        $acdstartmonth.addClass('tempCannot').attr('data-click','');
                }

                if(startMonth.length<8||minDays<1)
                    return;


                minDays=parseInt(minDays);
                var dateArr=[];
                dateArr=this.getDateByInterval(startMonth,minDays);//获取开始日期和最少入住时间段内的日期，日期数组
                var flag=true;
                for(var i=0;i<dateArr.length;i++)//判断日期数组中是否有已出租或不可选的日期，如果有，则flag为false
                {
                    if(i!=dateArr.length-1)
                    {
                        var $acdstartmonth= $('.acd-day-bg[id='+dateArr[i]+']');
                        if(!$acdstartmonth.hasClass('thisday'))
                            $acdstartmonth.addClass('tempCannot').attr('data-click','');
                    }


                    if(_box.opts.invalidDate.indexOf(dateArr[i])>=0||_box.opts.invalidChooseDate.indexOf(dateArr[i])>=0||_box.opts.unknownDateStr.indexOf(dateArr[i])>=0)
                    {
                        if(i!=dateArr.length-1)//最后一个日期可以不必是可选状态
                        {
                            flag=false;
                            break;
                        }
                    }
                }
                if(flag) //日期中没有包含不可选日期，则如果最后一项日期原本已出租状态，设置为可选，其后的一项设置为不可选，对应条件7
                {
                    var _curObj=null;
                    if(!dateArr)
                        return;
                    //for(var i=0;i<dateArr.length;i++)
                    //{
                    _curObj= $('.acd-day-bg[id='+dateArr[dateArr.length-1]+']');
                    var $nextNode=_curObj.parent().next();
                    if(_curObj.hasClass('day-previous'))
                    {
                        var showday=parseInt(_curObj.attr('id').substring(6,8));

                        _curObj.removeClass('day-previous notChoose alreadySend').addClass('data-hover')
                            .attr('data-click','ok').html(showday)
                            .parent().removeClass('preNode').addClass('normalNode selfalready');

                        if(_curObj.hasClass('alreadySend')) //如果退房日期原本是已出租的，则其下一个节点设置为不可选
                        {
                            if($nextNode.hasClass('normalNode'))
                            {
                                $nextNode.removeClass('normalNode').addClass('preNode')
                                    .find('.acd-day-bg').removeClass('data-hover').addClass('day-previous')
                                    .attr('data-click','');
                            }
                        }

                    }

                    //}
                }
                else { //如果日期数组中包含不可选日期，则开始日期和最少入住天数之间的日期全置为不可选
                    //for(var i=0;i<minDays;i++)
                    //{
                    var _curObj=null;
                    for(var i=0;i<dateArr.length;i++)
                    {
                        _curObj= $('.acd-day-bg[id='+dateArr[i]+']');
                        if(_curObj.hasClass('data-hover'))
                        {
                            _curObj.removeClass('data-hover').addClass('day-previous')
                                .attr('data-click','')
                                .parent().removeClass('normalNode').addClass('preNode');
                        }
                    }
                    //}
                }



                if(!_box.opts.hasChangeed)//没有被修改过
                {
                    //选择退房日期时，后面的第一个退房或不可租日期设置为可退房，它后面的一个日期设置为不可退房
                    var inOrOut = _box.getSingleOption('inOrOut');

                    if(inOrOut &&dateArr.length>0) //如果是退房日期
                    {
                        var tempid=dateArr[dateArr.length-1];
                        var $curparent=$('[id='+tempid+']').parent();
                        if(!$curparent.hasClass('selfalready')){
                            $nextchangeday=$curparent.nextAll('.aleadysendbox');
                            if($nextchangeday.length>0)
                            {
                                $nextchangeday=$nextchangeday.filter(':eq(0)');//要修改的目标节点
                                $nextchangeday.removeClass('preNode');
                                var $nextdaybg=$nextchangeday.find('.acd-day-bg');
                                var dayshow=$nextdaybg.attr('id');

                                dayshow=dayshow.substring(dayshow.length-2,dayshow.length);
                                dayshow=parseInt(dayshow);
                                $nextdaybg.removeClass('day-previous notChoose alreadySend').addClass('data-hover').attr('data-click','ok');//设置改为可退房

                                var $nextnochange=$nextchangeday.next();
                                if(!$nextnochange.hasClass('aleadysendbox')){ //下一个如果是正常，则设置为不可租
                                    // $nextnochange.removeClass('data-hover').addClass('day-previous alreadySend').attr('data-click','');//设置改为可退房
                                }
                                _box.opts.hasChangeed=1;
                            }

                            else  //判断是否是下个月的
                            {
                                var $firstday=$('.acd-month-box .nornalD:eq(0)');
                                var firstdayid=$firstday.find('.acd-day-bg').attr('id');
                                if(parseInt(firstdayid)>parseInt(startMonth)){
                                    if($firstday.hasClass('aleadysendbox')){

                                        $firstday.removeClass('preNode');
                                        var $nextdaybg=$firstday.find('.acd-day-bg');


                                        var dayshow=firstdayid.substring(firstdayid.length-2,firstdayid.length);
                                        dayshow=parseInt(dayshow);
                                        $nextdaybg.removeClass('day-previous notChoose alreadySend').addClass('data-hover').html(dayshow).attr('data-click','ok');//设置改为可退房

                                        var $nextnochange=$firstday.next();
                                        if(!$nextnochange.hasClass('aleadysendbox')){ //下一个如果是正常，则设置为不可租
                                            $nextnochange.removeClass('data-hover').addClass('day-previous alreadySend').attr('data-click','');//设置改为可退房
                                        }
                                        _box.opts.hasChangeed=1;


                                    } else {
                                        var firstday=$('.aleadysendbox').find('.acd-day-bg').attr('id');
                                        var $nextdaybg=$('.aleadysendbox').find('.acd-day-bg');
                                        var dayshow=firstday.substring(firstdayid.length-2,firstday.length);
                                        dayshow=parseInt(dayshow);
                                        $nextdaybg.removeClass('day-previous notChoose alreadySend').addClass('data-hover').html(dayshow).attr('data-click','ok');//设置改为可退房

                                    }
                                }
                            }


                        }






                    }




                }

            }
            catch(e){
                console.log(e);
            }
        },

        /***检测两个日期之间是否有不可选的日期
         * tempoldMonth 小日期
         * clickValue 大日期
         * ***/
        testDate:function(tempoldMonth,clickValue){
            var tempnext=$('.acd-day-bg[id='+tempoldMonth+']').parent().next(); //小日期的后一个
            var tempprev=$('.acd-day-bg[id='+clickValue+']').parent().prev(); //大日期的前一个
            var interval=0;
            interval= this.getDateDeff(tempoldMonth,clickValue);
            var flag=0;
            if(interval<parseInt(this.opts.minNights))
            {
                flag=-1;
                return flag;
            }
            for(var i=0;i<interval-1;i++)
            {
                if(tempnext.hasClass('preNode'))
                {
                    flag=-2;
                    break;
                }
                else {
                    tempnext=tempnext.next();
                }

                if(tempprev.hasClass('preNode'))
                {
                    flag=-2;
                    break;
                }
                else {
                    tempprev=tempprev.prev();
                }
            }
            return flag;
        },
        // 月份数字转汉字
        monthToText:function (month) {
            var monthText;
            month = String(month);
            switch(month){
                case '01': monthText = $.i18n.prop('f15d36d0eedf60bc47052c40db294007');break;
                case '02': monthText = $.i18n.prop('4ec385ff8325271d2814ae875008edeb');break;
                case '03': monthText = $.i18n.prop('2a51aa70299e5059deaa7c31c01c71c9');break;
                case '04': monthText = $.i18n.prop('e004f2a3f66d007aaa1a3308a0008683');break;
                case '05': monthText = $.i18n.prop('590b9c8928e9985428163fa7f339b1c8');break;
                case '06': monthText = $.i18n.prop('9bb5858792adec4675b7bb95c5b30ba8');break;
                case '07': monthText = $.i18n.prop('9e46b3ed441a48f858e8f1d453279b38');break;
                case '08': monthText = $.i18n.prop('95c5a6c25cfff25aa74b272f8156191c');break;
                case '09': monthText = $.i18n.prop('7d82ae2f3707ccb433e5edbd283f6b78');break;
                case '10': monthText = $.i18n.prop('3023b31e2b4c51f7d722d9ba229f3514');break;
                case '11': monthText = $.i18n.prop('ab6cb0b4f1765e66ec272560dc12c30a');break;
                case '12': monthText = $.i18n.prop('7addd1b7be576d0a1325d492516e13e1');break;
		//default : monthText = '十一';
            }
            return monthText;
        },
        /***
         * 计算两个日期月份差
         * @param smallDate 例如'201708'
         * @param bigDate 例如'201609'
         */
        getMouthInterval:function (smallDate,bigDate) {
            var smallYear = Number(smallDate.substr(0,4));
            var smallMouth = Number(smallDate.substr(4,2));
            var bigYear = Number(bigDate.substr(0,4));
            var bigMouth = Number(bigDate.substr(4,2));
            return (bigYear-smallYear)*12+(bigMouth-smallMouth);
        }






    }//appCalendar end



})(jQuery);
